<?php

function getValues($sFile,$sPart) {
	
	$sPart = strtolower($sPart);
	$aValues = $aIndexes = $aResult = array();
	
	$sFileData = file_get_contents($sFile); // reading file content
	$oXmlParser = xml_parser_create('UTF-8');
	
	xml_parse_into_struct($oXmlParser, $sFileData, $aValues, $aIndexes);
	xml_parser_free( $oXmlParser );
	 
	$aTagIndexes = $aIndexes['ITEM'];
	if (count($aTagIndexes) <= 0) {
		exit;
	}
	 
	foreach($aTagIndexes as $iTagIndex) {
		$sValue = $aValues[$iTagIndex]['value'];
		if (strpos(strtolower($sValue), $sPart) !== false) {
			$aResult[] = $sValue;
		}
	}
	
	return $aResult;

}

/*  */
   $sPart = ( isset($_POST['q']) ) ? $_POST['q'] : $_GET['q'];

   if (! $sPart ) exit;
   
   if (version_compare(phpversion(), "5.3.0", ">=")  == 1)
   		error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
   else
   		error_reporting(E_ALL & ~E_NOTICE);

   $result = array();
   $medicines = getValues('medicines.xml', $sPart );
   $compounds = getValues('compounds.xml', $sPart );
   
   if ( count($medicines) > 0 ) {
      $result['Medicamento'] = $medicines;
   }
   
   if ( count($compounds) > 0 ) {
   	  $result['Componente Activo'] = $compounds;
   }
   
   echo json_encode($result);

?>
